package com.orange.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;


@Service
public class UtilInterface {
	private static final Logger log = Logger.getLogger(UtilInterface.class);

	public static final String code_yes = "200";

	@Autowired
	private AppConfig appConfig;

	public String sendGetRequestAddHead(String url, String Cookie)
			throws UnsupportedEncodingException {
		String data = "";
		HttpClient client = new HttpClient();
		Integer socketTimeout = 10000;
		Integer connectionTimeout = 10000;
		// final int retryTime = 3;
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				socketTimeout);
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
		client.getParams()
				.setParameter(CoreConnectionPNames.TCP_NODELAY, false);
		client.getParams().setParameter(
				CoreConnectionPNames.SOCKET_BUFFER_SIZE, 1024 * 1024);
		StringBuilder sb = new StringBuilder();
		InputStream ins = null;
		GetMethod method = new GetMethod(url);
		method.setRequestHeader("Cookie", Cookie);
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));
		try {
			int statusCode = client.executeMethod(method);
			// System.out.println(statusCode);
			if (statusCode == HttpStatus.SC_OK) {
				ins = method.getResponseBodyAsStream();
				byte[] b = new byte[1024];
				int r_len = 0;
				while ((r_len = ins.read(b)) > 0) {
					sb.append(new String(b, 0, r_len, method
							.getResponseCharSet()));
				}
				if(sb.toString().contains("false")){
					log.error("同桌100激活接口异常错误：url:"+url+",时间："+System.currentTimeMillis()+",cookie:"+Cookie);
				}
			} else {
				sb.delete(0, sb.length());
				sb.append("-1");
				log.error("请求接口失败,url:" + url);
			}
		} catch (Exception e) {
			sb.delete(0, sb.length());
			sb.append("-1");
			log.error("请求接口失败,url:" + url);
			log.error("请求接口失败,errmsg:" + e.getMessage());
		} finally {
			method.releaseConnection();
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
					log.error("请求接口失败,url:" + url);
					log.error("请求接口失败,errmsg:" + e.getMessage());
				}
			}
			data = new String(sb.toString().getBytes("ISO-8859-1"), "utf-8");
			log.info(data);
		}
		return data;
	}

	public String sendGetRequest(String url) {
		HttpClient client = new HttpClient();
		Integer socketTimeout = 10000;
		Integer connectionTimeout = 10000;
		// final int retryTime = 3;
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				socketTimeout);
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
		client.getParams()
				.setParameter(CoreConnectionPNames.TCP_NODELAY, false);
		client.getParams().setParameter(
				CoreConnectionPNames.SOCKET_BUFFER_SIZE, 1024 * 1024);
		String data = "";
		StringBuilder sb = new StringBuilder();
		InputStream ins = null;
		GetMethod method = new GetMethod(url);
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));
		try {
			int statusCode = client.executeMethod(method);
			System.out.println(statusCode);
			if (statusCode == HttpStatus.SC_OK) {
				ins = method.getResponseBodyAsStream();
				byte[] b = new byte[1024];
				int r_len = 0;
				while ((r_len = ins.read(b)) > 0) {
					sb.append(new String(b, 0, r_len, method
							.getResponseCharSet()));
				}
			} else {
				sb.delete(0, sb.length());
				sb.append("-1");
				log.error("请求接口失败,url:" + url);
			}
		} catch (Exception e) {
			sb.delete(0, sb.length());
			sb.append("-1");
			log.error("请求接口失败,url:" + url);
			log.error("请求接口失败,errmsg:" + e.getMessage());
		} finally {
			method.releaseConnection();
			if (ins != null) {
				try {
					ins.close();
					data = new String(sb.toString().getBytes("ISO-8859-1"),
							"utf-8");
				} catch (IOException e) {
					log.error("请求接口失败,url:" + url);
					log.error("请求接口失败,errmsg:" + e.getMessage());
				}
			}
			log.info(data);
		}
		return data;
	}

	@SuppressWarnings("rawtypes")
	public String sendPostRequest(String url, Object obj) {
		HttpClient client = new HttpClient();
		Integer socketTimeout = 10000;
		Integer connectionTimeout = 10000;
		// final int retryTime = 3;
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				socketTimeout);
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
		client.getParams()
				.setParameter(CoreConnectionPNames.TCP_NODELAY, false);
		client.getParams().setParameter(
				CoreConnectionPNames.SOCKET_BUFFER_SIZE, 1024 * 1024);
		StringBuilder sb = new StringBuilder();
		InputStream ins = null;
		PostMethod method = new PostMethod(url);
		method.setRequestHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=utf-8");
		NameValuePair[] param = null;
		try {
			/* if(obj instanceof BaseModel){ */
			Class type = obj.getClass();
			BeanInfo beanInfo = Introspector.getBeanInfo(type);
			PropertyDescriptor[] propertyDescriptors = beanInfo
					.getPropertyDescriptors();
			param = new NameValuePair[propertyDescriptors.length - 1];
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					Method readMethod = descriptor.getReadMethod();
					Object result = readMethod.invoke(obj, new Object[0]);
					if (result != null) {
						param[i - 1] = new NameValuePair(propertyName,
								result.toString());
					} else {
						param[i - 1] = new NameValuePair(propertyName, "");
					}
				}
			}
			/*
			 * }else{ sb.delete(0, sb.length()); sb.append("-1");
			 * log.error("参数类别无法识别！,type:" + obj.getClass()); }
			 */
			method.setRequestBody(param);
			int statusCode = client.executeMethod(method);
			if (statusCode == HttpStatus.SC_OK) {
				ins = method.getResponseBodyAsStream();
				byte[] b = new byte[1024];
				int r_len = 0;
				while ((r_len = ins.read(b)) > 0) {
					sb.append(new String(b, 0, r_len, method
							.getResponseCharSet()));
				}
			} else {
				sb.delete(0, sb.length());
				sb.append("-1");
				log.error("请求接口失败,url:" + url);
			}
		} catch (Exception e) {
			sb.delete(0, sb.length());
			sb.append("-1");
			log.error("请求接口失败,url:" + url);
			log.error("请求接口失败,errmsg:" + e.getMessage());
		} finally {
			method.releaseConnection();
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
					log.error("请求接口失败,url:" + url);
					log.error("请求接口失败,errmsg:" + e.getMessage());
				}
			}
			log.info(sb.toString());
		}
		return sb.toString();
	}

/*	public BaseModel getBaseModel(Object param) throws Exception {
		String key = "===========";
		JSONObject json = JSONObject.fromObject(param);
		String paramReal = json.toString();
		BaseModel baseModel = new BaseModel(TimeUtil.nowDate(), "401",
				paramReal, "zh-u", "");
		String sign = baseModel.getTime() + key + baseModel.getSource()
				+ paramReal;
		sign = DigestUtils.md5DigestAsHex(sign.getBytes("UTF-8"));
		sign = DigestUtils.md5DigestAsHex((sign + key + baseModel.getLang())
				.getBytes("UTF-8"));
		baseModel.setSign(sign);
		return baseModel;
	}*/

	public String getReturnJson(String jsonString) {
		JSONObject json = JSONObject.fromObject(jsonString);
		String code = json.getString("code");
		if (UtilInterface.code_yes.equals(code)) {
			return json.getString("param");
		}
		return "";
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String sendPostImageRequest(String url,MultipartFile PreviewImage,String cookiejson, Map map) throws UnsupportedEncodingException{
		String data = "";
		//上传图片
		File imgFile = null;
		HttpClient client = new HttpClient();
		StringBuilder sb = new StringBuilder();
		InputStream ins = null;
		PostMethod method=new PostMethod("http://ask.tongzhuo100.com/ask_xiaoxin_submit.php");
		Iterator iter = map.keySet().iterator();
		try
		{
			String fileName = PreviewImage.getOriginalFilename();  
			//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名  
	        String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());  
	        //对扩展名进行小写转换  
	        ext = ext.toLowerCase();  
	        
	        
	        //新的图片文件名
	        String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + "." + ext;
			imgFile = new File(newFileName);  //System.getProperty("user.dir")
			PreviewImage.transferTo(imgFile); 
			
            Part[] parts = null; 
            if(!PreviewImage.isEmpty()){
            	parts = new Part[map.size()+1] ;
            }else{
            	parts = new Part[map.size()] ;
            }
            
            int i = 0;
            while (iter.hasNext()) {
	        	String key = (String)iter.next();
	        	String value = (String) map.get(key);
	        	parts[i] = new StringPart(key, value ,"utf-8");
	        	i++;
			}
            if(!PreviewImage.isEmpty()){
            	parts[parts.length-1] = new FilePart("PreviewImage", imgFile);
            }
			/*method.setParameter("titles", (String) map.get("titles"));
			method.setParameter("Contents", (String) map.get("Contents"));
			method.setParameter("Grades", (String) map.get("Grades"));
			method.setParameter("Courses", (String) map.get("Courses"));*/
            method.getParams().setContentCharset("utf-8");
            MultipartRequestEntity mre = new MultipartRequestEntity(parts, method.getParams());  
            method.setRequestEntity(mre);
			
			method.setRequestHeader("Cookie", cookiejson);
			
			client.executeMethod(method);
			
			if (method.getStatusCode() == HttpStatus.SC_OK){
				ins = method.getResponseBodyAsStream();
				byte[] b = new byte[1024];
				int r_len = 0;
				while ((r_len = ins.read(b)) > 0) {
					sb.append(new String(b, 0, r_len, method.getResponseCharSet()));
				}
			} 
		} catch (Exception ex){
			ex.printStackTrace();
		} finally {
			method.releaseConnection();
			imgFile.delete();
			data = new String(sb.toString().getBytes("utf-8"),"utf-8");
			log.info(data);
		}
		return data;
	}
}